<template>
  <a-modal
    v-model:visible="visible"
    :title="modalTitle"
    :width="modalWidth"
    :maskClosable="false"
    :destroyOnClose="true"
    :footer="null"
    wrapClassName="custom-modal min-base-modal"
    @cancel="handleCancel"
  >
    <a-row :gutter="24">
      <a-col :span="10">
        <div class="mb-4">
          <a-spin tip="正在加载..." :spinning="fgloading">
            <img
              :src="frameUrl"
              @click="() => setVisible(true)"
              class="h-[14rem] m-auto cursor-pointer"
            />
          </a-spin>
        </div>
        <a-row>
          <a-col :span="12">
            <span class="text-[#4E5969] mr-2">监控区域:</span>
            <span class="text-[#1D2129]">{{ loadDefectData?.areaName }}</span>
          </a-col>
          <a-col :span="12" v-if="+loadDefectData?.pointType === 2">
            <span class="text-[#4E5969] mr-2">电压等级:</span>
            <span class="text-[#1D2129]">
              {{ loadDefectData?.voltageLevel }}
            </span>
          </a-col>
          <a-col :span="12" v-else>
            <span class="text-[#4E5969] mr-2">线路:</span>
            <span class="text-[#1D2129]">{{ loadDefectData?.lineName }}</span>
          </a-col>
        </a-row>
        <a-row class="mt-1" v-if="+pointType !== 1">
          <a-col :span="12">
            <span class="text-[#4E5969] mr-2">监控设备:</span>
            <span class="text-[#1D2129]">{{ loadDefectData?.cameraName }}</span>
          </a-col>
          <a-col :span="12">
            <!-- TODO 无人机则无预置位；相机是枪机则无预置位 -->
            <span class="text-[#4E5969] mr-2">预置位:</span>
            <span class="text-[#1D2129]">
              {{ loadDefectData?.positionName }}
            </span>
          </a-col>
        </a-row>
        <a-row class="mt-1">
          <a-col :span="12">
            <span class="text-[#4E5969] mr-2">检测时间:</span>
            <span class="text-[#1D2129]">{{ loadDefectData?.algTime }}</span>
          </a-col>
        </a-row>
        <div class="mt-4" v-if="+pointType === 1">
          <a-spin tip="正在加载..." :spinning="unloading">
            <!-- <img
              :src="unripUrl"
              @click="() => setUnripVisible(true)"
              class="h-[14rem] m-auto cursor-pointer"
            /> -->
            <img
              :src="unripUrl"
              @click="toPage"
              class="h-[14rem] m-auto cursor-pointer"
            />
          </a-spin>
        </div>

        <!-- TODO 此处只为可预览图片 -->
        <a-image
          :style="{ display: 'none' }"
          :preview="{
            visible: imageVisible,
            onVisibleChange: setVisible
          }"
          :src="frameUrl"
        />
        <a-image
          :style="{ display: 'none' }"
          :preview="{
            visible: unripVisible,
            onVisibleChange: setUnripVisible
          }"
          :src="unripUrl"
        />
      </a-col>
      <a-col :span="14">
        <div class="bg-[#f7f8fa] rounded px-4 py-4">
          <div class="flex">
            <div class="text-[#4E5969] w-[5.375rem]">缺陷设备名:</div>
            <span class="text-[#1D2129]">{{ modalData.deviceName }}</span>
          </div>
          <div class="flex mt-2">
            <div class="text-[#4E5969] w-[4.375rem]">运行编号:</div>
            <span class="text-[#1D2129]">{{ modalData.runNum }}</span>
          </div>
        </div>
        <div class="font-[700] mt-4 mb-3">设备缺陷详情</div>
        <a-table
          :dataSource="dataSource"
          :pagination="false"
          :columns="columns"
          :loading="loading"
          :customRow="(record: any) => {
              return {
                onClick:()=> handleClickRow(record)
              }
            }
          "
          rowClassName="cursor-pointer"
        >
          <template #bodyCell="{ column, index }">
            <template v-if="column.dataIndex === 'order'">
              {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
            </template>
          </template>
        </a-table>
        <div class="mt-3 h-8">
          <Pagination @getListByPage="getListByPage" ref="paginationRef" />
        </div>
      </a-col>
    </a-row>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, createVNode } from 'vue'
// import { message } from 'ant-design-vue'
import { Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { detailList, loadDefectDetail } from './serve.api'

// @ts-ignore
import { unpick, frame } from '@/utils/grap'

// const emit = defineEmits(['isOk'])

const router = useRouter()

const imageVisible = ref<boolean>(false)
const unripVisible = ref<boolean>(false)
const setVisible = (value: any) => {
  imageVisible.value = value
}
const setUnripVisible = (value: any) => {
  unripVisible.value = value
}

const visible = ref<boolean>(false)
const loading = ref<boolean>(false)
const fgloading = ref<boolean>(false)
const unloading = ref<boolean>(false)

const dataSource = ref()
const paginationRef = ref()

const modalTitle = ref('')
const modalWidth = ref('')
const modalData = ref()

const loadDefectData = ref()
const pointType = ref('')
const frameUrl = ref()
const unripUrl = ref()

const pagination = reactive({
  total: 0,
  pageSize: 10, // 每页中显示10条数据
  position: ['bottomCenter'],
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`
})

const columns = ref([
  {
    title: '序号',
    dataIndex: 'order',
    width: '6rem'
  },
  {
    title: '部件名称',
    dataIndex: 'partName',
    key: 'partName',
    ellipsis: true
  },
  {
    title: '缺陷结果',
    dataIndex: 'defectResult',
    key: 'defectResult',
    ellipsis: true
  },
  {
    title: '检测时间',
    dataIndex: 'algTime',
    key: 'algTime',
    ellipsis: true
  }
])

function loadDefectFun(data: any) {
  pointType.value = data.pointType

  fgloading.value = true
  frameUrl.value = ''
  unloading.value = true
  unripUrl.value = ''

  loadDefectDetail({ id: data.id }).then((res) => {
    if (res) {
      console.log(res, '加载详情', res.uavSeqResult)
      loadDefectData.value = res

      // TODO 画框
      getPicFrame(res.imagePath, res.bbox).then((i) => {
        frameUrl.value = i
        fgloading.value = false
      })

      if (res.uavSeqResult) {
        // 无人机分割数据
        const { imagePath, maskImagePath, resultDetailList } = res.uavSeqResult

        // TODO 先分割，再去画框(有效避免分割图覆盖框)
        // getPicUnrip(imagePath, maskImagePath, resultDetailList).then((x) => {
        //   getPicFrame(x as string, resultDetailList).then((y) => {
        //     unripUrl.value = y
        //     unloading.value = false
        //   })
        // })

        unpick(imagePath, maskImagePath, resultDetailList).then((x: string) => {
          frame(x, resultDetailList).then((y: string) => {
            unripUrl.value = y
            unloading.value = false
          })
        })
      } else {
        unloading.value = false
      }
    }
  })
}

// 初始化数据
const getList = (flag = false) => {
  // if (flag) {
  //   pagination.current = 1
  //   paginationRef.value.changeCurrent(pagination.current)
  // }
  loading.value = true
  dataSource.value = []

  const params = {
    deviceId: modalData.value.deviceId,
    pageNum: pagination.current,
    pageSize: pagination.pageSize
  }

  detailList(params)
    .then((res) => {
      if (res) {
        console.log(res, '设备缺陷列表')
        loadDefectFun(res.list[0])

        dataSource.value = res.list
        pagination.total = res.total

        paginationRef.value.changeTotal(pagination.total)
        loading.value = false
      } else {
        loading.value = false
      }
    })
    .catch(() => {
      loading.value = false
    })
}

const getListByPage = (page: number, pageSize: number) => {
  if (pagination.current !== page) {
    pagination.current = page
    getList()
  }
  if (pagination.pageSize !== pageSize) {
    pagination.pageSize = pageSize
    getList(true)
  }
}

const currentRow = ref<any>({})
function handleClickRow(record: any) {
  console.log('点击了行', record)
  currentRow.value = record
  loadDefectFun(record)
}

const showModal = (data?: any) => {
  visible.value = true
  modalData.value = data
  modalTitle.value = '设备详情'
  modalWidth.value = '66%'
  getList(true)
}

// 图像画框
function getPicFrame(url: string, data: any | string) {
  return new Promise((resolve) => {
    const image = new Image()
    image.src = url
    image.setAttribute('crossOrigin', 'Anonymous')
    image.onload = () => {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      if (ctx) {
        canvas.width = image.width
        canvas.height = image.height
        ctx.drawImage(image, 0, 0, image.width, image.height)

        // TODO 判断 是否直接是坐标(单框)还是对象(多框)
        if (typeof data === 'string') {
          const xy = data.split(',').map(Number) // ['355', '2282', '851', '2998']

          const height = xy[3] - xy[1]
          const width = xy[2] - xy[0]

          // 添加文字
          // ctx.font = '3rem Microsoft YaHei'
          // ctx.fillStyle = `rgb(${i.bboxColor})` // 字色
          ctx.strokeStyle = '#f00' // 框色

          // ctx.fillText(i.deviceName, xy[0], xy[1] - 26)

          // 添加矩形框
          ctx.lineWidth = image.width / 400 // 框宽
          ctx.strokeRect(xy[0], xy[1], width, height)
        } else {
          data.forEach((i: any) => {
            const xy = i.bbox.split(',') // ['355', '2282', '851', '2998']

            const height = xy[3] - xy[1]
            const width = xy[2] - xy[0]

            // 添加文字
            // ctx.font = '3rem Microsoft YaHei'
            // ctx.fillStyle = `rgb(${i.bboxColor})`
            ctx.strokeStyle = `rgb(${i.bboxColor})`

            // ctx.fillText(i.deviceName, xy[0], xy[1] - 26)

            // 添加矩形框
            ctx.lineWidth = image.width / 400
            ctx.strokeRect(xy[0], xy[1], width, height)
          })
        }
      }

      const base64 = canvas.toDataURL('image/jpeg', 1)
      resolve(base64)
    }

    image.onerror = (_) => {
      resolve(undefined)
    }
  })
}

// 图像分割
// function getPicUnrip(url1: string, url2: string, data: any) {
//   return new Promise((resolve, reject) => {
//     const loadImage = (url: string) => {
//       return new Promise((_resolve, _reject) => {
//         const image = new Image()
//         image.crossOrigin = 'anonymous'
//         image.src = url
//         image.onload = () => _resolve(image)
//         image.onerror = _reject
//       })
//     }

//     const colors = {
//       // 1: { r: 215, g: 105, b: 105 },
//       // 添加更多标签和颜色
//     }

//     data.forEach((x: any, y: any) => {
//       const color = x.bboxColor.split(',')
//       colors[y + 1] = { r: color[0], g: color[1], b: color[2] }
//     })

//     Promise.all([loadImage(url1), loadImage(url2)])
//       .then(([imgA, imgB]) => {
//         const canvas = document.createElement('canvas')
//         const ctx = canvas.getContext('2d')

//         // 设置 canvas 尺寸与图片相同
//         canvas.width = imgA.width
//         canvas.height = imgA.height

//         // 绘制图像 a
//         ctx.drawImage(imgA, 0, 0)

//         // 获取图像 a 的图像数据
//         const imageDataA = ctx.getImageData(0, 0, imgA.width, imgA.height)
//         const pixelDataA = imageDataA.data

//         // 在不同的 canvas 上获取 b 的图像数据
//         const tempCanvas = document.createElement('canvas')
//         tempCanvas.width = imgB.width
//         tempCanvas.height = imgB.height
//         const tempCtx = tempCanvas.getContext('2d')
//         tempCtx.drawImage(imgB, 0, 0)
//         const imageDataB = tempCtx.getImageData(0, 0, imgB.width, imgB.height)

//         // 透明度因子（0 - 1之间，这里设为0.5表示半透明）
//         const alpha = 0.5

//         // 遍历像素并处理
//         for (let i = 0; i < imageDataB.data.length; i += 4) {
//           // 检查b图像的红色通道中的值，假设它是一个灰度图像
//           const labelValue = imageDataB.data[i] // 读取单通道的值

//           // 如果类别为water（你可以根据需要调整类别值）
//           if (colors[labelValue]) {
//             const { r, g, b } = colors[labelValue]

//             // 将 A 对应像素设为红色 修改RGB
//             pixelDataA[i + 0] = r * alpha + pixelDataA[i + 0] * (1 - alpha) // R
//             pixelDataA[i + 1] = g * alpha + pixelDataA[i + 1] * (1 - alpha) // G
//             pixelDataA[i + 2] = b * alpha + pixelDataA[i + 2] * (1 - alpha) // B
//             pixelDataA[i + 3] = 255 * alpha + pixelDataA[i + 3] * (1 - alpha) // A
//           }
//         }

//         // 将处理后的图像数据绘制回 canvas
//         ctx.putImageData(imageDataA, 0, 0)

//         // 创建合并后的画布
//         const resultCanvas = document.createElement('canvas')
//         resultCanvas.width = canvas.width
//         resultCanvas.height = canvas.height
//         const resultCtx = resultCanvas.getContext('2d')
//         resultCtx && resultCtx.drawImage(canvas, 0, 0)

//         // 将处理后的图像数据转换为 base64 格式
//         const base64 = resultCanvas.toDataURL('image/jpeg', 1)
//         resolve(base64)
//       })
//       .catch(reject)
//   })
// }

// 取消
const handleCancel = () => {
  visible.value = false
  // formRef.value?.resetFields()
}

function toPage() {
  Modal.confirm({
    title: '提示',
    icon: createVNode(ExclamationCircleOutlined),
    content: '是否要跳转至首页定位到设备上？',
    onOk() {
      const { tagId } = loadDefectData.value
      const { deviceId } = modalData.value

      router.push({
        path: '/',
        query: {
          tagId,
          deviceId
        }
      })
    },
    onCancel() {
      console.log('Cancel')
    }
  })
}

defineExpose({ showModal })
</script>
